package com.siblings.loan.ui.steps.view

import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.base.utils.DensityUtils
import com.siblings.loan.R
import com.siblings.loan.app.Apps
import com.siblings.loan.databinding.ItemStepContactBinding
import com.siblings.loan.http.ApiService.addCommonParams
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.steps.act.SibStepsAct
import com.siblings.loan.ui.steps.adapter.SibStepContactAdapter
import com.siblings.loan.utils.StringDeepCopy
import com.siblings.loan.utils.event.SibEventType
import org.json.JSONArray
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/10 15:13
 * @Annotation：步骤联系人样式
 */
class SibStepContactView(private val stepAct: SibStepsAct,private val stepData: JSONObject) {
    var binding = ItemStepContactBinding.inflate(stepAct.layoutInflater)

    @SuppressLint("StaticFieldLeak")
    private var contactAdapter: SibStepContactAdapter? = null

    init {
        initSibContactViews()
        initSibContactListener()
    }

    /**
     * 联系人样式
     */
    fun includeSibStepContactView(): View {
        return binding.root
    }

    /**
     * 初始化Views
     */
    private fun initSibContactViews(){
        //        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(stepAct)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
//        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        contactAdapter = SibStepContactAdapter(binding.root,binding.recyclerView)
        binding.recyclerView.adapter = contactAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 初始化事件监听
     */
    private fun initSibContactListener(){
        //添加一条联系人信息
        binding.addLayout.setOnClickListener {
            val lastItem = JSONObject(StringDeepCopy(contactAdapter!!.lastItem.toString()).content)
            val dataArray = lastItem!!.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataArray.optJSONObject(i).put("selectItem",null)
                }
            }
//            LogHelper.e(">>>>>>>>>>>>>>>>>>>>>>>>"+lastItem.toString())
            contactAdapter!!.addLastItem(lastItem)
        }

        //提交
        binding.btnNext.setOnClickListener {
            if (!isAllowContactSubmit()){
                stepAct.showSibTipsDialog(stepData.optString("stepTitle"))
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path",stepData!!.optString("apiUrl").replace("/",""))
            }
            //拼接上传数据格式
            val paramArray = JSONArray()
            for (i in 0..<contactAdapter!!.itemCount){
                val obj = JSONObject()
                val dataArray = contactAdapter!!.getItem(i).optJSONArray("dataList")
                for (j in 0..<dataArray!!.length()){
                    val item = dataArray.optJSONObject(j)
                    obj.put(item.optString("paramName"),item.optJSONObject("selectItem").optString("value"))
                }
                paramArray.put(obj)
            }
            params.put(stepData!!.optString("contactParamName"),paramArray)
            stepAct.mvpPresenter.onSibSubmitProcessAction(params)

            HttpHelper.addSibEventAction(String.format(SibEventType.CLICK.SIB_CLICK_STEP_XX_NEXT, stepData.optString("stepTitle")),"")
        }
    }

    /**
     * 设置联系人列表数据
     */
    fun setSibContactListData(contactList: ArrayList<JSONObject>){
        contactAdapter!!.data = contactList
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowContactSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<contactAdapter!!.itemCount){
            val dataArray = contactAdapter!!.getItem(i).optJSONArray("dataList")
            for (j in 0..<dataArray!!.length()){
                val item = dataArray.optJSONObject(j)
                dataList.add(item)
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    fun onDestroy(){
        if (contactAdapter != null){
            contactAdapter = null
        }
    }
}